# Go parameters
GOCMD=go
GOBUILD=$(GOCMD) build
GOCLEAN=$(GOCMD) clean
GOTEST=$(GOCMD) test
GORUN=$(GOCMD) run

# Binary name
BINARY_NAME=nginxConfigFormatterGo
OUTPUT_DIR=build
LOCAL_BIN=$(OUTPUT_DIR)/local

OS_ARCHES = \
    linux/amd64 \
    linux/arm64 \
    darwin/arm64 \
    windows/amd64 \
    windows/arm64

os = $(word 1,$(subst /, ,$1))
arch = $(word 2,$(subst /, ,$1))
outdir = $(OUTPUT_DIR)/$(call os,$1)/$(call arch,$1)
exe_suffix = $(if $(filter windows,$(1)),.exe,)

RELEASE_TARGETS = $(foreach target,$(OS_ARCHES),build-$(subst /,-,$(target)))

# All Targets
all: build

# Build the binary for the host platform
build:
	@mkdir -p $(LOCAL_BIN)
	$(GOBUILD) -o $(LOCAL_BIN)/$(BINARY_NAME) .

# Run the application
run: build
	./$(LOCAL_BIN)/$(BINARY_NAME)

# Run tests
test:
	$(GOTEST) -v ./...

# Clean the artifacts
clean:
	$(GOCLEAN)
	rm -rf $(OUTPUT_DIR)

# Cross compilation matrix
release: $(RELEASE_TARGETS)

define build_template
build-$(subst /,-,$(1)): clean
	@mkdir -p $(OUTPUT_DIR)
	GOOS=$(call os,$(1)) GOARCH=$(call arch,$(1)) CGO_ENABLED=0 $(GOBUILD) -o $(OUTPUT_DIR)/$(BINARY_NAME)_$(call os,$1)_$(call arch,$1)$(call exe_suffix,$(call os,$(1))) .
endef

$(foreach target,$(OS_ARCHES),$(eval $(call build_template,$(target))))

.PHONY: all build run test clean release $(RELEASE_TARGETS)